package com.star.mall.mq.comsumer;

import cn.hutool.json.JSONUtil;
import com.star.mall.constants.TopicConstant;
import com.star.mall.persistence.entity.OperationLog;
import com.star.mall.persistence.service.IOperationLogService;
import lombok.extern.log4j.Log4j2;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * kafka消费者
 * @author StarQ
 * @since 2021-3-10
 */
@Component
@ConditionalOnProperty(
        prefix = "jms",
        name = {"mode"},
        havingValue = "kafka",
        matchIfMissing = true
)
@Log4j2
public class KafkaConsumer {

    @Resource
    IOperationLogService operationLogService;

    @KafkaListener(topics = {TopicConstant.OPERATION_LOG})
    public void onMessage(ConsumerRecord<String, String> r){
        OperationLog log = JSONUtil.toBean(r.value(), OperationLog.class);
        operationLogService.save(log);
    }

    @KafkaListener(topics = {TopicConstant.ERROR_LOG})
    public void onErrorMessage(ConsumerRecord<String, String> r) {
        // Do nothing
    }

}
